import Vue from 'vue';
import VueI18n from 'vue-i18n';

import { getLanguage } from '@/lib/auth';

// vant 语言
import elementEnLocale from 'vant/lib/locale/lang/en-US';
import elementZhLocale from 'vant/lib/locale/lang/zh-CN';
import elementEsLocale from 'vant/lib/locale/lang/es-ES';
import elementJaLocale from 'vant/lib/locale/lang/ja-JP';
import elementKoLocale from 'vant/lib/locale/lang/ro-RO';

// 公共语言
import enLocale from '../en';
import zhLocale from '../zh';
import esLocale from '../es';
import jaLocale from '../ja';
import koLocale from '../ko';
import itLocale from '../it';

Vue.use(VueI18n);

export const messages = {
  en: {
    ...enLocale,
    ...elementEnLocale
  },
  zh: {
    ...zhLocale,
    ...elementZhLocale
  },
  es: {
    ...esLocale,
    ...elementEsLocale
  },
  ja: {
    ...jaLocale,
    ...elementJaLocale
  },
  ko: {
    ...koLocale,
    ...elementKoLocale
  },
  it: {
    ...itLocale
  }
};

/**
 * 获取本地语言
 */
export const getLocale = () => {
  const cookieLanguage = getLanguage();
  if (cookieLanguage) {
    return cookieLanguage;
  }

  const language = navigator.language.toLowerCase();
  const locales = Object.keys(messages);
  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      return locale;
    }
  }

  // 默认英文语言
  return 'en';
};

const i18n = new VueI18n({
  locale: getLocale(),
  messages
});

export default i18n;
